package com.netty.junjie.socket.server;

import com.netty.junjie.socket.impl.NettyChannelInitializerImpl;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * *
 * NettyBufServer 初始化Server
 *
 * @author JunJie
 * @Date 2020/07/13 07:13
 **/
@Component
@Slf4j
public class NettyBufServer {
    @Resource
    private NettyChannelInitializerImpl nettyChannelInitializer;

    @Value("${netty.nettyPort.port}")
    private int nettyPort;

    public void bind() throws Exception {
        // 配置服务端的NIO线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 100)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childHandler(nettyChannelInitializer);
            // 绑定端口，同步等待成功
            ChannelFuture f = b.bind(nettyPort).sync();
            log.debug("Netty服务初始化,服务端口: " + nettyPort);
            // 等待服务端监听端口关闭
            f.channel().closeFuture().sync();
        } finally {
            // 优雅退出，释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


}
